package com.lbloca.locate.utils;

import com.google.gson.internal.$Gson$Types;
import com.zhy.http.okhttp.callback.StringCallback;

import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;

import okhttp3.Call;


public abstract class CommonCallback<T> extends StringCallback {
    Type mType;

    public CommonCallback() {
        mType = getSuperclassTypeParameter(getClass());
    }

    static Type getSuperclassTypeParameter(Class<?> subclass) {
        Type superclass = subclass.getGenericSuperclass();
        if (superclass instanceof Class) {
            throw new RuntimeException("Missing type parameter.");
        }
        ParameterizedType parameterized = (ParameterizedType) superclass;
        return $Gson$Types.canonicalize(parameterized.getActualTypeArguments()[0]);
    }

    @Override
    public void onError(Call call, Exception e, int id) {
        onError(e);
    }

    public abstract void onError(Exception e);

    public abstract void onSuccess(T response);

    @Override
    public void onResponse(String response, int id) {
        try {
//            Log.e("response", "response :" + response);
            onSuccess((T) GsonUtil.getGson().fromJson(response, mType));
        } catch (Exception e) {
            e.printStackTrace();
            onError(e);
        }
    }
}
